import { NextRequest, NextResponse } from "next/server"; import { getServerSession } from 'next-auth'; import { authOptions } from '@/app/api/auth/[...nextauth]/route'; import db from "@/db/db"; import { eq } from "drizzle-orm"; import { rfqLastAttachments, rfqLastAttachmentRevisions } from "@/db/schema"; import { deleteFile } from "@/lib/file-stroage"; export async function DELETE( request: NextRequest, { params }: { params: { id: string } } ) { try { const session = await getServerSession(authOptions); if (!session?.user?.id) { return NextResponse.json( { success: false, message: "인증이 필요합니다" }, { status: 401 } ); } const attachmentId = parseInt(params.id); // 트랜잭션 시작 const result = await db.transaction(async (tx) => { // 1. 첨부파일 정보 조회 const [attachment] = await tx .select() .from(rfqLastAttachments) .where(eq(rfqLastAttachments.id, attachmentId)); if (!attachment) { throw new Error("첨부파일을 찾을 수 없습니다"); } // 2. 모든 리비전 조회 const revisions = await tx .select() .from(rfqLastAttachmentRevisions) .where(eq(rfqLastAttachmentRevisions.attachmentId, attachmentId)); // 3. 모든 리비전 파일 삭제 (공용 삭제 함수 사용) for (const revision of revisions) { if (revision.filePath) { await deleteFile(revision.filePath); } } // 4. 리비전 레코드 삭제 await tx .delete(rfqLastAttachmentRevisions) .where(eq(rfqLastAttachmentRevisions.attachmentId, attachmentId)); // 5. 첨부파일 레코드 삭제 await tx .delete(rfqLastAttachments) .where(eq(rfqLastAttachments.id, attachmentId)); return attachment; }); return NextResponse.json({ success: true, message: "파일이 삭제되었습니다", data: result, }); } catch (error) { console.error("Delete attachment error:", error); return NextResponse.json( { success: false, message: error instanceof Error ? error.message : "파일 삭제 실패" }, { status: 500 } ); } }